package labilabyrinth.activity;

import java.io.FileNotFoundException;

import labilabyrinth.enums.EditMode;
import labilabyrinth.game.R;
import labilabyrinth.level.editor.LevelEditor;
import labilabyrinth.level.editor.LevelManager;
import labilabyrinth.serializable.FinishHole;
import labilabyrinth.serializable.Hole;
import labilabyrinth.serializable.Level;
import android.app.Activity;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class LevelEditorActivity extends Activity{
	
	private LevelEditor editor;
	private LevelManager lManager;
	private String levelName;
	private int levelIndex;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        levelName = extras.getString("level_name");
        levelIndex = extras.getInt("level_index");
        setTitle("Editing "+levelName);
        editor = new LevelEditor(this);
        setContentView(editor);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, R.string.add_obstacle);
		menu.add(0, 1, 1, R.string.add_ball);
		menu.add(0, 2, 2, R.string.add_deadly_hole);
		menu.add(0, 3, 3, R.string.add_finish_hole);
		menu.add(0, 4, 4, "Save");
		menu.add(0, 5, 5, "Clear");
		return true;
	}

    public void saveLevel(){
    	lManager = new LevelManager(this);
    	Level levelToSave =  new Level(levelIndex,levelName);
    	levelToSave.setBallPosition(editor.ballPos.x, editor.ballPos.y);
    	levelToSave.addHole(new FinishHole(editor.elementsSize, editor.finishHolelPos.x, editor.finishHolelPos.y));
    	for(Hole h:editor.holes)
    		levelToSave.addHole(h);
    	for(RectF r:editor.obstacles){
    		levelToSave.addObstacle(r);
    	}
    	try {
			if(lManager.saveLevel(levelToSave)){
				Toast t = Toast.makeText(this.getApplicationContext(), R.string.lvl_saved, Toast.LENGTH_SHORT);
				t.show();
			}else{
				Toast t = Toast.makeText(this.getApplicationContext(), R.string.lvl_saved_failed, Toast.LENGTH_SHORT);
				t.show();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
    }
    
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			editor.setMode(EditMode.OBSTACLE);
			break;
		case 1:
			editor.setMode(EditMode.BALL_POS);
			break;
		case 2:
			editor.setMode(EditMode.DEADLY_HOLE);
			break;
		case 3:
			editor.setMode(EditMode.FINISH_HOLE);
			break;
		case 4:
			saveLevel();
			break;
		case 5:
			editor.clearMap();
			break;
		}
		return true;
	}
	
}
